package TrafficControlSystem.TrafficServer;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public abstract class RequestHandler
{

	public RequestHandler(Socket clientSocket)
	{
		super();
		this.clientSocket = clientSocket;
	}

	public boolean isConnectionAlive()
	{
		return clientSocket != null && clientSocket.isConnected()
				&& !clientSocket.isClosed();
	}

	public abstract void handle();

	public static RequestHandler createHandler(Socket clientSocket)
	{
		if (clientSocket == null || !clientSocket.isConnected() || clientSocket.isClosed())
			return null;

		try
		{
			InputStream in = clientSocket.getInputStream();
			byte character;
			StringBuffer buffer = new StringBuffer("");
			while ((character = (byte) in.read()) != -1) {
				if ((byte) character == '\n' || (byte) character == '\r')
					break;
				buffer.append((char) character);
			}
			in.read();
			
			String firstLine = buffer.toString();
			System.out.println("New request: " + firstLine);
			Logger.log("New request: " + firstLine);

			if (firstLine == null)
			{
				return null;
			} else if (firstLine.equals("GETINTENSITY")) {
				return new GETINTENSITYRequestHandler(clientSocket);
			} else if (firstLine.equals("GETLIGHTS")) {
				return new GETLIGHTSRequestHandler(clientSocket);
			} else if (firstLine.equals("SETCARS")) {
				return new SETCARSRequestHandler(clientSocket);
			} else if (firstLine.equals("SETLIGHTS")) {
				return new SETLIGHTSRequestHandler(clientSocket);
			} else if (firstLine.equals("SETINTENSITY")) {
				return new SETINTENSITYRequestHandler(clientSocket);
			}
		}
		catch (IOException e)
		{
			//e.printStackTrace();
			System.out.println("Client disconnected");
			return null;
		}

		return null;
	}

	protected Socket clientSocket;
}
